package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gaojun
 * @description ContextApplication
 * @date 2022/7/3 16:34
 */
public class GaoJunContextApplication {

    //配置类
    private Class Config;
    //bean定义缓存Map
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    //单例池
    private Map<String, Object> singletonObjects = new HashMap<>();
    //bean后置处理器
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public GaoJunContextApplication(Class config) {
        this.Config = config;
        //扫描Bean
        scan();
        //获取bean定义创建bean实例对象（单例）
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton") && !beanDefinition.isLazy()) { //判断是否单例
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    /**
     * 创建bean
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();
            for (Field filed : clazz.getDeclaredFields()) {
                if (filed.isAnnotationPresent(Autowired.class)) {
                    filed.setAccessible(true);
                    filed.set(instance, getBean(filed.getName()));
                }
            }
            if (instance instanceof BeanNameAware) {
                BeanNameAware aware = (BeanNameAware) instance;
                aware.setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            if (instance instanceof InitializingBean) {
                InitializingBean initializingBean = (InitializingBean) instance;
                initializingBean.afterPropertiesSet();
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return instance;
    }

    /***
     * 扫描bean
     */
    private void scan() {
        if (Config.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) Config.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();
            path = path.replace(".", "/");
            ClassLoader classLoader = GaoJunContextApplication.class.getClassLoader();
            URL url = classLoader.getResource(path);
            File file = new File(url.getFile());
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    String filePath = f.getAbsolutePath();
                    filePath = filePath.substring(filePath.indexOf("com"), filePath.indexOf(".class"));
                    filePath = filePath.replace("\\", ".");
                    try {
                        Class<?> clazz = classLoader.loadClass(filePath); //加载类
                        //判断是否是不是Bean
                        if (clazz.isAnnotationPresent(Component.class)) {
                            //判断是不是Bean的后置处理器
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.getConstructor().newInstance();
                                beanPostProcessorList.add(beanPostProcessor);
                                continue;
                            }
                            Component componentAnnotation = clazz.getAnnotation(Component.class);
                            String beanName = componentAnnotation.value();
                            if ("".equals(beanName)) {
                                beanName = Introspector.decapitalize(clazz.getSimpleName());
                            }
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(clazz);
                            //判断是否有Scope注解
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                String value = scopeAnnotation.value();
                                beanDefinition.setScope(value);
                            } else {
                                beanDefinition.setScope("singleton");
                            }
                            if (clazz.isAnnotationPresent(Lazy.class)) {
                                Lazy lazyAnnotation = clazz.getAnnotation(Lazy.class);
                                boolean value = lazyAnnotation.value();
                                beanDefinition.setLazy(value);
                            } else {
                                beanDefinition.setLazy(false);
                            }
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /***
     * 获取bean
     * @param beanName
     * @return
     */
    public Object getBean(String beanName) {
        if (!beanDefinitionMap.containsKey(beanName)) {
            throw new NullPointerException("没有找到符合要求的bean");
        }
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        String scope = beanDefinition.getScope();
        if ("singleton".equals(scope)) { //单例的直接从单例池中获取
            Object singletonBean = singletonObjects.get(beanName);
            if (singletonBean == null) { //注入依赖时如果单例池中没有则创建
                singletonBean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, singletonBean);
            }
            return singletonBean;
        } else {
            return createBean(beanName, beanDefinition);
        }
    }
}
